"""
auth-xgtpython
datetime:2021/11/9
Python通过接口下载网易云音乐
"""
# 导入相关的模块
import requests
import re
import execjs

url = 'https://music.163.com/discover/toplist?id=197233756'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',

}

# 拿到网页源代码 --
response = requests.get(url,headers)
data_html = response.text
# print(data_html)
# print(response.text)
# 2. 提取我们真正想要的 音乐的名称 id
# bs4 css xpath re正则表达式
# <li><a href="/song?id=1891469546">删了吧</a></li>
zip_data = re.findall('<li><a href="/song\?id=(.*?)">(.*?)</a></li>',data_html)

# 下载音乐 ：id获取是为了下载音乐
# 百度接口 使用下载 http://music.163.com/song/media/outer/url?id=
# 通过js逆向破解 加密参数直接下载
    # JavaScrpt
# 通过python去调用js代码 实现链接参数加密
js = open('music163_20211027_224640.js', mode='r', encoding='utf-8').read()
ctx = execjs.compile(js)

for music_id,title in zip_data:
   result = ctx.call('start',music_id)
   print(result)

    # url_1 = ' http://music.163.com/song/media/outer/url?id=' + music_id
    # 发送请求
    #  通过js逆向爬取数据
    # 当前的音乐数据
    # text 文本数据 content 二进制数据
    # music_data = requests.get(url_1,headers).content
    # f = open('music/' + title + '.mp3',mode='wb')
    # f.write()
    # f.close()
    # title = re.sub(r'[/\\:*?"<>|]','_',title)
    # with open('music/'+ title + '.mp3',mode='wb') as file:
    #     file.write(music_data)
    # print(title + "爬取成功!!!")







